import React, { useEffect, useState, useRef } from "react";
import {
  InfiniteScroll,
  PullToRefresh,
  DotLoading,
  Empty
} from "antd-mobile";
import styles from './index.module.less'
import DetailModal from '@/components/detail-modal'
import { showErrorToast } from '@/utils/customToast'
const { getWorldBookList, getWorldCategoryList } = $globalServicer('home')
import { worldType } from '@/utils/constant'

const GetPullToRefreshlData = React.forwardRef((props, ref) => {
  const { activeKey, selectedCategories = [], onCategoryChange, allCategoriesMap = new Map() } = props;
  const PageSize = 10;
  const [activeCategoryId, setActiveCategoryId] = useState(activeKey);
  
  
  const [page, setPage] = useState(1);
  const [listData, setListData] = useState([]);
  const [categoryList, setCategoryList] = useState([]);
  const [searchValue, setSearchValue] = useState('');
  const [hasMore, setHasMore] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [loading, setLoading] = useState(false);
  const [noData, setNoData] = useState(false);
  const [isInitialized, setIsInitialized] = useState(false);
  const [sortType, setSortType] = useState('view'); // 'view' 热度排序, 'id' 时间排序
  
  const abortControllerRef = useRef(null); // 保留但不使用，避免其他地方引用报错
  const requestIdRef = useRef(0); // 用于标识最新的请求
  
  // 组件卸载时取消pending的请求
  useEffect(() => {
    return () => {
      if (abortControllerRef.current) {
        abortControllerRef.current.abort();
      }
    };
  }, []);
  
  // 弹窗相关状态
  const [modalVisible, setModalVisible] = useState(false);
  const [selectedWorldId, setSelectedWorldId] = useState(null);
  
  
  
  const fetchData = React.useCallback(async (currentPage = page, categoryId = activeCategoryId, sort = sortType, selectedCats = selectedCategories, searchKey = searchValue) => {
    try {
      // 单选逻辑：如果有选中的子分类，使用子分类ID作为category_id
      const finalCategoryId = selectedCats.length > 0 ? selectedCats[0] : categoryId;
      
      const params = {
        page: currentPage,
        size: PageSize,
        key: searchKey,
        category_id: finalCategoryId,
        sort: sort, // 添加排序参数
        // 单选时，sub_category_ids和category_id是同一个值
        ...(selectedCats.length > 0 && { sub_category_ids: selectedCats[0] })
      }
      
      const response = await getWorldBookList(params);
      
      // 确保返回的是真正的数组
      const result = Array.isArray(response.data) ? response.data : [];
      return result;
    } catch (error) {
      showErrorToast("加载失败，请稍后再试");
      return [];
    }
  }, []); // 移除依赖，简化逻辑

  const resetStates = () => {
    setPage(1);
    setListData([]);
    setNoData(false);
    setHasMore(true);
    setIsInitialized(false);
  };

  const resetAllStates = () => {
    resetStates();
  };

  const fetchCategoryList = async (categoryId) => {
    try {
      const response = await getWorldCategoryList(categoryId);
      // 根据API返回结构处理数据
      const categoryData = response.data || response;
      if (Array.isArray(categoryData)) {
        setCategoryList(categoryData);
      } else {
        setCategoryList([]);
      }
    } catch (error) {
      showErrorToast("加载失败，请稍后再试");
      return [];
    }
  };

  // 根据category_id获取分类名称
  const getCategoryName = (categoryId) => {
    // 优先从全局分类映射中查找
    if (allCategoriesMap.has(categoryId)) {
      return allCategoriesMap.get(categoryId);
    }
    
    // 如果全局映射中没有，再从当前分类列表中查找
    const category = categoryList.find(cat => cat.id === categoryId);
    return category ? category.name : '';
  };

  const InfiniteScrollContent = ({ hasMore }) => {
    return (
      <>
        {hasMore ? (
          <>
            {/*<span style={{ fontSize: '16px' }}>Loading</span>*/}
            {/*<DotLoading />*/}
          </>
        ) : (
          <span style={{ fontSize: '16px' }}>--- 已到达底部 ---</span>
        )}
      </>
    )
  }

  const loadMoreData = async () => {
    if (!isInitialized || !hasMore || loading) return;
    
    try {
      setLoading(true);
      const newData = await fetchData(page, activeCategoryId, sortType, selectedCategories, searchValue);
      
      if (newData.length === 0) {
        setHasMore(false);
        return;
      }
      
      setListData((prevData) => [...prevData, ...newData]);
      setPage((prevPage) => prevPage + 1);
      
      if (newData.length < PageSize) {
        setHasMore(false);
      }
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    const loadCategoryData = async () => {
      if (activeKey === activeCategoryId && isInitialized) return;

      resetAllStates();
      setActiveCategoryId(activeKey);
      setCategoryList([]);
      setSearchValue('');
      
      try {
        setLoading(true);
        await fetchCategoryList(activeKey);
        const newData = await fetchData(1, activeKey, sortType, selectedCategories, searchValue);
        
        if (newData.length === 0) {
          setNoData(true);
          setHasMore(false);
        } else {
          setListData(newData);
          if (newData.length < PageSize) {
            setHasMore(false);
          }
          setPage(2);
        }
      } finally {
        setLoading(false);
        setIsInitialized(true);
      }
    };

    loadCategoryData();
  }, [activeKey]);

  useEffect(() => {
    // 只有在初始化完成后才响应搜索值变化
    if (!isInitialized || activeKey !== activeCategoryId) return;
    
    // 使用新的统一方法
    loadData(activeCategoryId, searchValue, selectedCategories);
  }, [searchValue]);


  const handleRefresh = async () => {
    if (refreshing) return;
    
    setRefreshing(true);
    try {
      await loadData(activeCategoryId, searchValue, selectedCategories, true);
      setIsInitialized(true);
    } finally {
      setRefreshing(false);
    }
  };


  // 处理列表项点击事件
  const handleItemClick = (worldId) => {
    setSelectedWorldId(worldId);
    setModalVisible(true);
  };

  // 关闭弹窗
  const handleCloseModal = () => {
    setModalVisible(false);
    setSelectedWorldId(null);
  };


  // 统一的数据加载方法，使用请求ID来避免竞态条件
  const loadData = async (categoryId, searchKey = '', selectedCats = [], resetData = true) => {
    // 生成新的请求ID - 这是当前应该显示的数据的ID
    const currentRequestId = ++requestIdRef.current;
    
    try {
      setLoading(true);
      
      if (resetData) {
        // 重置状态
        setPage(1);
        setHasMore(true);
        setNoData(false);
        setActiveCategoryId(categoryId);
        setSearchValue(searchKey);
        
        // 如果当前有数据，保持显示但显示loading状态
        // 如果当前没有数据，则清空避免显示错误的空状态
        if (listData.length === 0) {
          setListData([]);
        }
      }
      
      // 发起请求
      const newData = await fetchData(1, categoryId, sortType, selectedCats, searchKey);
      
      // 只检查请求ID，确保只有最新的请求才能更新数据
      if (requestIdRef.current !== currentRequestId) {
        // 如果有更新的请求，忽略这个结果
        return;
      }
      // 更新数据 - 只有最新的请求才能更新数据
      if (newData.length === 0) {
        setListData([]); // 清空数据
        setNoData(true);
        setHasMore(false);
      } else {
        setListData(newData); // 设置新数据（会自动替换旧数据）
        setNoData(false);
        if (newData.length < PageSize) {
          setHasMore(false);
        } else {
          setHasMore(true);
        }
        setPage(2);
      }
    } catch (error) {
      // 只有最新请求才处理错误
      if (requestIdRef.current === currentRequestId) {
        console.error('加载数据失败:', error);
        setNoData(true);
        setListData([]);
      }
    } finally {
      // 只有最新请求才重置loading状态
      if (requestIdRef.current === currentRequestId) {
        setLoading(false);
      }
    }
  };

  // 使用useImperativeHandle暴露方法给父组件调用
  React.useImperativeHandle(ref, () => ({
    // 新的统一方法
    loadData,
    // 兼容性方法（可选）
    triggerCategoryFilter: () => loadData(activeCategoryId, searchValue, selectedCategories),
    triggerCategoryFilterWithParams: (customSelectedCategories) => 
      loadData(activeCategoryId, searchValue, customSelectedCategories),
    setSearchValue: (value) => {
      if (value !== searchValue) {
        loadData(activeCategoryId, value, selectedCategories);
      }
    }
  }));

  return (
    <div>
      <PullToRefresh
        key={activeKey}
        onRefresh={handleRefresh}
        refreshing={refreshing}
      >

        {/* Loading状态显示 - 放在列表最上方 */}
        {loading && (
            <div className={styles.loadingContainer}>
              <div className={styles.loadingContent}>
                <DotLoading color={getComputedStyle(document.documentElement).getPropertyValue('--theme-primary').trim()}/>
                <div className={styles.loadingText}>正在加载，请稍等...</div>
              </div>
            </div>
        )}

        <div className={styles.listWrapper}>
          {listData.map((item, index) => (
              <div key={item.id} className={styles.card} onClick={() => handleItemClick(item.id)}>
                <div className={styles.imageContainer}>
                  <div
                      className={styles.itemImage}
                  style={{ backgroundImage: `url(${item.cover})`, backgroundSize: 'cover' }}
                >
                  {/* 移除分类徽章，不再在图片上显示 */}
                </div>
              </div>
              <div className={styles.contentArea}>
                <div className={styles.titleRow}>
                  <h3 className={styles.title}>{item.name}</h3>
                  <span className={styles.author}>{item.user_name}</span>
                </div>
                <div className={styles.descriptionContainer}>
                  <p className={styles.description}>{item?.description}</p>
                </div>
                <div className={styles.bottomRow}>
                  <div className={styles.tagsContainer}>
                    {/* 显示分类名称而不是worldType */}
                    <span className={styles.tag}>{getCategoryName(item.category_id)}</span>
                  </div>
                </div>
              </div>
            </div>
          ))}
          {
            (() => {
              console.log(`🖼️ 渲染检查: listData.length=${listData.length}, noData=${noData}, loading=${loading}`);
              return noData && <div style={{ width: '100%', margin: 'auto' }}><Empty description='暂无数据' /></div>;
            })()
          }
          <InfiniteScroll 
            loadMore={loadMoreData} 
            hasMore={hasMore} 
            threshold={100}
            disabled={!isInitialized || loading}
          >
            <InfiniteScrollContent hasMore={hasMore} />
          </InfiniteScroll>
        </div>
      </PullToRefresh>
      
      {/* 详情弹窗 */}
      <DetailModal 
        visible={modalVisible}
        onClose={handleCloseModal}
        worldId={selectedWorldId}
      />
    </div>
  );
});

export default React.memo(GetPullToRefreshlData);
